import React, { useEffect, useRef, useState } from 'react'
import { message, Modal } from 'antd'
import { connect, history } from '@umijs/max'
import list2tree from 'list2tree'
import { CheckCircleOutlined } from '@ant-design/icons'
import {
 InputSearch, ProTable, ProTableOperate, ProTableOptions, ProTree, searchTreeListByName,
} from '@/components'
import { getProjectId } from '@/utils/https'
import Tools from '@/utils/Tools'
import { TestModal } from './page-components'
import styles from './index.less'

const { OperateItem } = ProTableOperate
const { confirm } = Modal

const getNavTreeDataFunc = list2tree({
  idKey: 'id',
  parentIdKey: 'pid',
  newKey: {
    key: 'id',
    value: 'id',
    title: 'dirName',
  },
})

// 获取该id下所有的子id
const getAllChildrenId = (dataRef) => {
  const tempArr = [dataRef.id]
  if (dataRef.children) {
    dataRef.children.map((item) => {
      // eslint-disable-next-line prefer-spread
      tempArr.push.apply(tempArr, getAllChildrenId(item))
      return null
    })
  }
  return tempArr
}

const ApiMarket = (props) => {
  const [treeData, setTreeData] = useState([])
  const [treeDataNew, setTreeDataNew] = useState([])
  const [selectedKeys, setSelectedKeys] = useState([])
  const [query, setQuery] = useState({})
  const [inpValue, setInpValue] = useState('')
  const [forceUpdate, setForceUpdate] = useState(0)
  // const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [loading, setLoading] = useState(false)
  const [optTypeParams, setOptTypeParams] = useState(null)
  const testModalRef = useRef()
  const tableRef = useRef()
  let tree

  useEffect(() => {
    getTreeThemes()
  }, [])

  useEffect(() => {
    if (inpValue === '') {
      fetchData()
    }
  }, [inpValue])

  // 获取左侧列表方法
  const getTreeThemes = () => {
    // 标记每个节点是第几层children
    const signLayerNum = (item, num = 0) => {
      item.layerNum = num
      if (num >= 5) {
        item.icon = true
      }
      item?.children?.map((child) => {
        const tempNum = num + 1
        signLayerNum(child, tempNum)
        return null
      })
    }
    props.dispatch({
      type: 'apiMarket/queryGetApiGroup',
      cb: (data) => {
        const arr = getNavTreeDataFunc(data) || []
        setTreeData(data || [])
        setTreeDataNew(arr)
      },
    })
  }

  const columns = [
    {
      title: 'API名称',
      dataIndex: 'apiName',
      key: 'apiName',
      width: '18%',
      // ellipsis: true,
      render: (apiName) => (apiName || '-'),
    },
    {
      title: 'API描述',
      dataIndex: 'apiDesc',
      key: 'apiDesc',
      width: '18%',
      // ellipsis: true,
      render: (apiDesc) => (apiDesc || '-'),
    },
    {
      title: '累计调用次数',
      dataIndex: 'totalCount',
      key: 'totalCount',
      width: '15%',
      // ellipsis: true,
      render: (totalCount) => (totalCount || '-'),
    },
    {
      title: '创建人',
      dataIndex: 'username',
      key: 'username',
      width: '15%',
      // ellipsis: true,
      render: (username) => (username || '-'),
    },
    {
      title: '发布时间',
      dataIndex: 'publishTime',
      key: 'publishTime',
      width: '15%',
      // ellipsis: true,
      render: (publishTime) => (publishTime || '-'),
    },
    {
      title: '操作',
      // dataIndex: 'space',
      key: 'operate',
      render: (record) => {
        const { id, apiType, approveStatus } = record
        return (
          <ProTableOptions>
            <span onClick={() => {
              (apiType === 0 || apiType === 1) && history.push(`/data-service/api-manage/produce-api-detail?id=${id}&type=market`)
              apiType === 2 && history.push(`/data-service/api-manage/register-api-detail?id=${id}&type=market`)
              apiType === 3 && history.push(`/data-service/api-manage/index-api-detail?id=${id}&type=market`)
            }}
            >查看
            </span>
            <span onClick={() => { queryTestApi(id) }}>测试</span>
            {
              ((approveStatus !== 0 && approveStatus !== 1) || null) && (
                <span onClick={() => { queryApplyApiById(id) }}>申请使用</span>
              )
            }
            {
              (approveStatus === 0 || null) && (
                <span onClick={() => {
                  history.push('/data-service/api-manage/my-apply?activeKey=0')
                }}
                >已申请
                </span>
              )
            }
            {
              (approveStatus === 1 || null) && (
                <span onClick={() => {
                  history.push('/data-service/api-manage/my-apply?activeKey=1')
                }}
                >已申请
                </span>
              )
            }
            <span onClick={() => { onExport([id]) }}>导出</span>
          </ProTableOptions>
        )
      },
    },
  ]

  // 测试
  const queryTestApi = (apiId) => {
    setLoading(true)
    props.dispatch({
      type: 'apiMarket/queryGetApiTestInfo',
      params: {
        apiId,
      },
      cb: (res) => {
        const { status, data, msg } = res
        setLoading(false)
        if (status === 200) {
          // forceUpdateFn()
          testModalRef?.current?.toggleModal(data, apiId)
        } else {
          message.error(msg || '服务端错误')
        }
      },
    })
  }

  // 申请使用
  const queryApplyApiById = (apiId) => {
    setLoading(true)
    props.dispatch({
      type: 'apiMarket/queryApplyApiById',
      params: {
        apiId,
      },
      cb: (res) => {
        const { status, msg } = res
        setLoading(false)
        if (status === 200) {
          showConfirm()
          setQuery({ ...query })
        } else {
          message.error(msg || '服务端错误')
        }
      },
    })
  }

  const onSelect = (selectedKeysParams, node) => {
    node?.node?.id === 0 ? setSelectedKeys([0]) : setSelectedKeys(getAllChildrenId(node.node))
    // 重置表格选中的数据
    tableRef?.current?.resetSelectedRowKeys()
    tableRef?.current?.resetPageNum()
    setQuery({
      ...query,
      groupId: node?.node?.id === 0 ? '' : getAllChildrenId(node.node).join(','),
    })
  }

  const fetchData = () => {
    const tempQuery = {}
    tempQuery.apiName = inpValue
    setQuery({
      ...query,
      ...tempQuery,
      groupId: selectedKeys[0] === 0 ? '' : selectedKeys.join(','),
    })
  }

  // const forceUpdateFn = () => {
  //   setForceUpdate(forceUpdate + 1)
  //   getTreeThemes()
  // }

  // 批量导出
  const onExport = (idArr) => {
    const selectedRowKeys = idArr?.length ? idArr : tableRef?.current?.state.selectedRowKeys
    // console.log('selectedRowKeys', selectedRowKeys)
    if (selectedRowKeys.length < 1) {
      message.warning('请至少选择一条数据')
      return null
    }
    let idsStr = ''
    selectedRowKeys.map((item) => {
      if (idsStr !== '') idsStr += ','
      idsStr += item
      return null
    })
    // window.location.href = `/api/v1/apiMarket/exportApi?apiIds=${idsStr}&projectId=${getProjectId()}`
    Tools.downloadFile(`${window.suanpan}/api/v1/apiMarket/exportApi?apiIds=${idsStr}&projectId=${getProjectId()}`)
    return null
  }

  const rowSelection = {
    type: 'checkbox',
  }

  const showConfirm = () => {
    confirm({
      title: '提交申请成功',
      icon: <CheckCircleOutlined style={{ color: '#43a047' }} />,
      content: 'API名称申请提交成功，可前往我的申请列表查看API的申请状态',
      okText: '查看',
      width: '286px',
      closable: true,
      onOk() {
        history.push('/data-service/api-manage/my-apply?activeKey=0')
      },
      onCancel() {
        console.log('Cancel')
      },
    })
  }

  return (
    <div className={styles.standard_define}>
      <div className={styles.page_content}>
        <div className={styles.page_content_left}>
          <ProTree
            showLine
            showSearch
            width={208}
            showTitle={false}
            treeData={treeDataNew}
            selectedKeys={selectedKeys}
            onSelect={onSelect}
            ref={(dev) => (tree = dev)}
            search={(name) => {
              const searchTree = searchTreeListByName(
                name,
                treeData,
                'dirName',
              )
              const treeDataNews = getNavTreeDataFunc(
                searchTree.result,
              )
              // const dataSource = [
              //   {
              //     title: '全部分组',
              //     groupName: '全部分组',
              //     value: 0,
              //     key: 0,
              //     id: 0,
              //     children: treeDataNews,
              //   },
              // ]
              setTreeDataNew(treeDataNews)
              tree.onExpand(searchTree.fatchIds)
            }}
          />
        </div>
        <div className={styles.page_content_right}>
          <ProTableOperate>
            <OperateItem align="left">
              <InputSearch
                placeholder="请输入API名称进行搜索"
                value={inpValue}
                onChange={(e) => {
                  setInpValue(e.target.value)
                }}
                onSearch={fetchData}
              />
            </OperateItem>
          </ProTableOperate>
          <ProTable
            ref={tableRef}
            loading={loading}
            key={forceUpdate}
            url="/api/v1/apiMarket/getMarketList"
            query={query}
            rowKey="id" // key传递的是否有效，影响rowSelection的使用
            columns={columns}
            rowSelection={rowSelection}
            bulkOperation={[
              {
                title: '批量导出',
                loading: optTypeParams === 0 ? loading : false,
                // onClick: (params) => { batchOpt(params, 0) },
                onClick: onExport,
              },
            ]}
          />
        </div>
      </div>
      <TestModal ref={testModalRef} />
    </div>
  )
}

export default connect(({ apiMarket }) => ({ ...apiMarket }))(ApiMarket)
